package web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tuna.UserOp;

/**
 * Servlet implementation class getMessage
 */
public class sendMessage extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter out = response.getWriter();
		
		try {
			String utorId = request.getParameter("utorId");
			String userId = request.getParameter("userId");
			String receiverUtorId = request.getParameter("receiver");
			String detail = request.getParameter("detail");
			
			if (utorId == null || utorId.isEmpty() || userId == null || userId.isEmpty() || 
					receiverUtorId == null || receiverUtorId.isEmpty() || detail == null || detail.isEmpty()) {
				response.setContentType("text/xml");
				out.print("<message>Error: One of parameters is missed</message>");
				return;
			}
			
			String message;
			
			int intId = Integer.parseInt(userId);
			
			UserOp sender = new UserOp(utorId, intId);
			UserOp receiver = new UserOp(receiverUtorId);
			
			int receiverId = receiver.getUserIdFromSql();
			
			if(receiverId < 0) {
				message = "Error: Receiver does not exist";
			}
			else {
				if(sender.sendMessage(intId, receiverId, detail)) {
					message = "Message delivered successfully";
				}
				else {
					message = "Error: Exception at SQL level";
				}
			}
						
			response.setContentType("text/xml");
			out.print("<response>");
			out.print("<message>" + message + "</message>");
			out.print("</response>");
		}
		catch (Exception ex) {
			response.setContentType("text/xml");
			out.print("<message>Error: Exception</message>");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(request, response);
	}

}
